from django.db import migrations
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
import os

def generate_thumbnails(apps, schema_editor):
    AntiqueImage = apps.get_model('antiques', 'AntiqueImage')
    for image in AntiqueImage.objects.all():
        if image.image and not image.thumbnail:
            try:
                # 创建缩略图
                img = Image.open(image.image)
                # 设置缩略图的最大尺寸
                max_size = (300, 300)
                img.thumbnail(max_size, Image.Resampling.LANCZOS)
                
                # 保存缩略图
                thumb_io = BytesIO()
                img.save(thumb_io, format='JPEG', quality=85)
                thumb_io.seek(0)
                
                # 生成缩略图文件名
                thumb_name = f"thumb_{os.path.basename(image.image.name)}"
                image.thumbnail.save(thumb_name, ContentFile(thumb_io.getvalue()), save=False)
                image.save()
            except Exception as e:
                print(f"Error processing image {image.id}: {str(e)}")

class Migration(migrations.Migration):
    dependencies = [
        ('antiques', '0006_antiqueimage_thumbnail'),
    ]

    operations = [
        migrations.RunPython(generate_thumbnails),
    ] 